<script setup>
import Fuse from 'fuse.js';
import { cloneDeep } from 'lodash-es';
import { getToken } from '@/utils/auth';
import { rulesPattern } from '@/utils/tools.js';
import { useRequest, useWatch, useDownload } from '@/hooks';
import { useGlobalState } from '@/store/globalState.js';
import { useSelectIns } from '@/store/zdwh.js';
import { getTreeData, getEditBuilding, addBuilding, editBuilding, importSave, deleteBuilding, getDownloadPath } from '@/api/index.js';
import { Message, MessageBox } from 'element-ui';
import ToolTip from '@/components/ToolTip/index.vue';

const selectIns = useSelectIns();
const defaultProps = {
  // 默认设置
  children: 'children',
  label: 'name',
};
const fileUrl = useGlobalState().globalState.fileUrl;
const tree = ref(null);
const currentData = ref(null);
const currentNode = ref(null);
const detailsData = ref(null);
const dialogData = ref({
  open1: false,
  open2: false,
  title: '',
});
const editForm = ref(null);
const editParams = ref({
  buildingViewId: null,
  buildingName: null,
  buildingArea: null,
  peopleNum: null,
  buildingImage: '',
  sortNum: null,
});
const pName = ref(null);
const addtop = ref(false);
const rules = ref({
  buildingViewId: { required: true, message: '请输入区域编号', trigger: 'blur' },
  buildingName: { required: true, message: '请输入区域名称', trigger: 'blur' },
  buildingImage: { required: false, message: '请上传区域缩略图', trigger: ['blur', 'change'] },
  sortNum: [
    { required: true, message: '请输入同级排序号', trigger: ['blur', 'change'] },
    { pattern: rulesPattern.pInteger0, message: '请输入正整数', trigger: ['blur', 'change'] },
  ],
});
const buildingImage = ref('');
const upload = ref({
  // 设置上传的请求头部
  headers: { Authorization: 'Bearer ' + getToken() },
  // 上传的地址
  url: useGlobalState().globalState.serverUrl + '/file/uploadFile',
  url2: useGlobalState().globalState.serverUrl + '/energyservice/building/import',
});
const uploadFile = ref(null);
const fileLists = ref([]);
const fileLists2 = ref([]);
const loading2 = ref(false);
const buildingValue = ref(null);
const tableData = ref([]);
const originalTableData = ref([]);
const uploadKey = ref(null);
const repetitiveMessage = ref(null);
const options = {
  keys: ['buildingViewId', 'buildingName'], // 搜索的键
  threshold: 0.4, // 阈值控制匹配的敏感度
};

const [res, loading, run] = useRequest(getTreeData, {
  manual: true,
  onSuccess: async res => {
    if (res?.data?.[0]?.id) {
      const obj = await getEditBuilding({ buildingCode: res?.data?.[0]?.id ?? '' });
      const imgUrl = await getDownloadPath(res?.data?.[0]?.buildingImage);
      detailsData.value = obj.data;
      detailsData.value.imgUrl=fileUrl+imgUrl.data.url;
      nextTick().then(() => {
        tree.value.setCurrentKey(detailsData.value?.buildingCode);
      });
    }else{
      detailsData.value.imgUrl='';
    }
  },
});
const [, , addRun] = useRequest(addBuilding, {
  manual: true,
  onSuccess: res => {
    if (res.code === 200) {
      Message.success(res.msg);
      cancel();
      addtop.value = false;
      run({ enterpriseCode: selectIns.selectIns?.enterpriseCode ?? '' });
    }
  },
});
const [, , editRun] = useRequest(editBuilding, {
  manual: true,
  onSuccess: res => {
    if (res.code === 200) {
      Message.success(res.msg);
      cancel();
      run({ enterpriseCode: selectIns.selectIns?.enterpriseCode ?? '' });
    }
  },
});
const [, , deleteRun] = useRequest(deleteBuilding, {
  manual: true,
  onSuccess: res => {
    if (res.msg === '操作成功') {
      Message.success(res.msg);
      run({ enterpriseCode: selectIns.selectIns?.enterpriseCode ?? '' });
    } else {
      Message.error(res.msg);
    }
  },
});
let fuse = new Fuse(tableData.value, options);

// 定义搜索函数
const searchData = query => {
  const results = fuse.search(query);
  return results.map(result => result.item);
};
const handleNodeClick = async (data, node, e) => {
  currentNode.value = node;
  pName.value = node.parent.data?.name ?? null;
  currentData.value = data;
  const obj = await getEditBuilding({ buildingCode: data?.id ?? '' });
  const imgUrl = await getDownloadPath(data?.buildingImage);
  detailsData.value = obj.data;
  detailsData.value.imgUrl=fileUrl+imgUrl.data.url;
};
const addTopNode = () => {
  dialogData.value.open1 = true;
  dialogData.value.title = '新增';
  addtop.value = true;
};
const addChildNode = async (node, data) => {
  dialogData.value.open1 = true;
  dialogData.value.title = '新增';
  currentData.value = data;
};
const editNode = async (node, data) => {
  dialogData.value.open1 = true;
  dialogData.value.title = '编辑';
  currentData.value = data;
  if (data.buildingImage?.length > 0) {
    fileLists.value = [
      {
        name: '',
        url: useGlobalState().globalState.serverUrl + data.buildingImage ?? '',
      },
    ];
  }
  await nextTick().then(() => {
    setTimeout(() => {
      editParams.value = cloneDeep(detailsData.value);
    }, 40);
  });
};
const removeNode = (node, data) => {
  MessageBox.confirm('删除后不可找回，是否确认删除', '提示', {
    confirmButtonText: '是',
    cancelButtonText: '否',
    type: 'warning',
  })
    .then(() => {
      deleteRun({ enterpriseCode: selectIns.selectIns?.enterpriseCode ?? '', buildingCode: data.id });
    })
    .catch(() => {});
};
const cancel = () => {
  dialogData.value.open1 = false;
  editForm.value.resetFields();
  editParams.value = {};
  fileLists.value = [];
  buildingImage.value = '';
};
const cancel2 = () => {
  dialogData.value.open2 = false;
  tableData.value = [];
  uploadKey.value = null;
  repetitiveMessage.value = null;
  fileLists2.value = [];
  tableData.value = [];
  originalTableData.value = [];
  buildingValue.value = null;
  uploadFile.value.clearFiles();
};
const beforeAvatarUpload = file => {
  let types = ['image/gif', 'image/jpg', 'image/png', 'image/jpeg', 'image/pneg'];
  const isImage = types.includes(file.type);
  const isLt2M = file.size / 1024 / 1024 < 5;
  if (!isImage) {
    Message.error('上传头像图片只能是 JPG、GIF、PNG 格式!');
  }
  if (!isLt2M) {
    Message.error('上传头像图片大小不能超过 5MB!');
  }
  return isImage && isLt2M;
};
const handleAvatarSuccess = (response, file, fileList) => {
  if (response.code === 200) {
    fileLists.value = fileList;
    buildingImage.value = response.data.url;
    editParams.value.buildingImage = response.data.url;
  } else {
    Message.error(response.msg);
    fileLists.value = [];
    buildingImage.value = '';
    editParams.value.buildingImage = null;
  }

  // editForm.value.validateField('buildingImage');
};
const handleRemove = () => {
  fileLists.value = [];
  buildingImage.value = '';
  editParams.value.buildingImage = null;
  // editForm.value.validateField('buildingImage');
};
const submitForm = () => {
  editForm.value.validate(valid => {
    if (valid) {
      if (dialogData.value.title === '新增') {
        MessageBox.confirm('请确认信息无误', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        }).then(() => {
          addRun({
            ...editParams.value,
            pBuildingCode: addtop.value ? '' : currentData.value?.id ?? '',
            level: '1',
            enterpriseCode: selectIns.selectIns?.enterpriseCode ?? '',
          });
        });
      } else if (dialogData.value.title === '编辑') {
        editRun(editParams.value);
      }
    } else {
      return false;
    }
  });
};
const handleDownload = () => {
  useDownload('/energyservice/building/templateDownload', {}, '建筑树模板.xlsx');
};
const handleUpload = () => {
  dialogData.value.open2 = true;
};
const handleAvatarSuccess2 = (response, file, fileList) => {
  fileLists2.value = fileList;
  if (response.code === 200) {
    Message.success('上传成功');
    originalTableData.value = response.data?.importEnBuildingTemplateList ?? [];
    tableData.value = response.data?.importEnBuildingTemplateList ?? [];
    uploadKey.value = response.data?.key;
    repetitiveMessage.value = response.data?.repetitiveMessage;
  } else {
    Message({
      type: 'error',
      message: response.msg,
    });
    fileLists2.value.splice(0, 1);
    uploadFile.value.clearFiles();
  }
};
const handleAvatarErroe2 = (err, file, fileList) => {
  Message({
    type: 'error',
    message: err?.msg ?? '上传失败，请重新上传',
  });
  fileLists2.value.splice(0, 1);
  uploadFile.value.clearFiles();
};
const handleUploadChange2 = (file, fileList) => {
  fileLists2.value = fileList;
};
const handleRemove2 = () => {
  fileLists2.value = [];
};
// 超出限制上传数量回调
const handleExceed2 = () => {
  Message({
    type: 'warning',
    message: '当前限制最大上传数量：1 ,上传新的文件之前请先删除原文件！',
  });
};
const addRedStar = (h, { column }) => {
  return [h('span', { style: 'color: #F56C6C' }, '*'), h('span', ' ' + column.label)];
};
const queryBuild = () => {
  if (!buildingValue.value || buildingValue.value?.length < 1) {
    tableData.value = originalTableData.value;
  } else {
    fuse = new Fuse(originalTableData.value, options);
    tableData.value = searchData(buildingValue.value);
  }
};
const saveUpload = () => {
  if (uploadKey.value?.length > 0) {
    if (repetitiveMessage.value?.length > 0) {
      MessageBox.confirm(repetitiveMessage.value, '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning',
      })
        .then(() => {
          useRequest(importSave, {
            defaultParams: [{ key: uploadKey.value }],
            onSuccess: res => {
              if (res.code === 200) {
                Message.success(res.msg);
                cancel2();
                run({ enterpriseCode: selectIns.selectIns.enterpriseCode });
              }
            },
          });
        })
        .catch(() => {});
    } else {
      MessageBox.confirm('请确认信息无误', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning',
      }).then(() => {
        useRequest(importSave, {
          defaultParams: [{ key: uploadKey.value }],
          onSuccess: res => {
            if (res.code === 200) {
              Message.success(res.msg);
              cancel2();
              run({ enterpriseCode: selectIns.selectIns.enterpriseCode });
            }
          },
        });
      });
    }
  } else {
    Message.warning('请上传文件');
  }
};
const changeRow = ({ row, rowIndex }) => {
  if (row?.updateFlag === '1') {
    return 'repeatRow';
  }
};
useWatch(
  () => selectIns.selectIns,
  n => {
    if (n) run({ enterpriseCode: n.enterpriseCode });
  },
  { deep: true, immediate: true },
);
</script>
<template>
  <div class="u-w100 u-h100 u-df-spb insBuild-wrapper">
    <div class="u-p20 u-mr20 u-base-fg">
      <div class="u-prim-text u-fs20">建筑树</div>
      <div class="u-mt20 u-mb20">
        <el-button size="small" type="primary" plain @click="addTopNode">添加顶级节点</el-button>
        <el-button size="small" type="primary" plain @click="handleUpload">导入建筑树</el-button>
        <el-button size="small" type="primary" plain @click="handleDownload">下载模板</el-button>
      </div>
      <el-tree
        ref="tree"
        v-loading="loading"
        :data="res"
        :props="defaultProps"
        :highlight-current="true"
        :current-node-key="detailsData?.buildingCode"
        node-key="id"
        @node-click="handleNodeClick"
      >
        <span class="custom-tree-node u-fs14" slot-scope="{ node, data }">
          <ToolTip class="tree-lable u-pr20" :content="data.name" effect="dark" />
          <!-- <span class="tree-lable u-pr20">{{ data.name }}</span> -->
          <span class="u-sec-text">
            <i class="toolBtn el-icon-circle-plus-outline u-mr5" @click="addChildNode(node, data)"></i>
            <i class="toolBtn el-icon-edit u-mr5" @click="editNode(node, data)"></i>
            <i v-show="node.isLeaf" class="toolBtn el-icon-delete" @click="removeNode(node, data)"></i>
          </span>
        </span>
      </el-tree>
    </div>
    <div class="u-p20 u-base-fg">
      <div class="u-prim-text u-fs20">区域详情</div>
      <div class="area-details">
        <div>
          <span>区域展示图</span>
          <img
            :src="detailsData?.imgUrl??''"
            alt="暂无图片"
            style="width: 363px; height: 204px"
          />
        </div>
        <div>
          <span>上级区域名称</span>
          <span>{{ pName ? pName : '-' }}</span>
        </div>
        <div>
          <span>区域编号</span>
          <span>{{ detailsData?.buildingViewId ?? '-' }}</span>
        </div>
        <div>
          <span>区域名称</span>
          <span>{{ detailsData?.buildingName ?? '-' }}</span>
        </div>
        <div>
          <span>建筑面积（㎡）</span>
          <span>{{ detailsData?.buildingArea ?? '-' }}</span>
        </div>
        <div>
          <span>办公人数</span>
          <span>{{ detailsData?.peopleNum ?? '-' }}</span>
        </div>
        <div>
          <span>同级排序号</span>
          <span>{{ detailsData?.sortNum ?? '-' }}</span>
        </div>
      </div>
    </div>
    <el-dialog :visible.sync="dialogData.open1" width="40%" :before-close="cancel" append-to-body>
      <div slot="title" class="dialog-title">
        <span class="tit">
          {{ dialogData.title }}-
          <span class="u-prim-text">建筑区域</span>
        </span>
      </div>
      <el-form
        v-loading="loading2"
        :model="editParams"
        ref="editForm"
        :rules="rules"
        size="small"
        label-width="130px"
        class="editForm u-pl20 u-pr20"
      >
        <el-form-item label="上级区域名称：" prop="">
          <span>{{ pName ? pName : '-' }}</span>
        </el-form-item>
        <el-form-item label="区域编号：" prop="buildingViewId">
          <el-input
            v-filter-input
            style="width: 100%"
            v-model.trim="editParams.buildingViewId"
            placeholder="请输入区域编号"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="区域名称：" prop="buildingName">
          <el-input
            v-filter-input
            style="width: 100%"
            v-model.trim="editParams.buildingName"
            placeholder="请输入区域名称"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="建筑面积（㎡）：" prop="buildingArea">
          <el-input
            v-filter-input
            style="width: 100%"
            v-model.trim="editParams.buildingArea"
            placeholder="请输入建筑面积"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="办公人数：" prop="peopleNum">
          <el-input
            v-filter-input
            style="width: 100%"
            v-model.trim="editParams.peopleNum"
            placeholder="请输入办公人数"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="区域缩略图：" prop="buildingImage">
          <el-upload
            class="uploadPic"
            :action="upload.url"
            list-type="picture-card"
            :limit="1"
            name="file"
            :show-file-list="true"
            :headers="upload.headers"
            :before-upload="beforeAvatarUpload"
            :file-list="fileLists"
            :on-success="handleAvatarSuccess"
            :on-remove="handleRemove"
            :class="{ styleA: fileLists.length === 0, styleB: fileLists.length === 1 }"
          >
            <i class="el-icon-plus"></i>
            <div v-if="fileLists.length === 0" slot="tip" class="el-upload__tip u-ml10 u-text">
              比例：16：9 格式：jpg.png.pneg.gif
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="同级排序号：" prop="sortNum">
          <el-input
            v-filter-input
            style="width: 100%"
            v-model.trim="editParams.sortNum"
            placeholder="请输入"
            clearable
            size="small"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancel" type="primary" plain>取 消</el-button>
        <el-button type="primary" size="small" @click="submitForm">保 存</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogData.open2" width="70%" :before-close="cancel2" append-to-body>
      <div slot="title" class="dialog-title">
        <span class="tit">
          <span class="u-prim-text">导入建筑树表</span>
        </span>
      </div>
      <div class="u-prim-text u-fs16">{{ selectIns.selectIns?.enterpriseName ?? '' }}</div>
      <el-upload
        ref="uploadFile"
        :file-list="fileLists2"
        :action="upload.url2"
        :data="{ enterpriseCode: selectIns.selectIns?.enterpriseCode }"
        :headers="upload.headers"
        :on-success="handleAvatarSuccess2"
        :on-error="handleAvatarErroe2"
        :on-change="handleUploadChange2"
        :on-remove="handleRemove2"
        :on-exceed="handleExceed2"
        :limit="1"
        accept=".xls,.xlsx,.xlsm"
        name="multiFile"
        class="upload-demo u-ml10 u-mt20"
      >
        <el-button size="small" plain class="el-icon-upload2" type="primary" style="font-size: 14px">
          点击上传文件
        </el-button>
        <span slot="tip" class="el-upload__tip u-ml10 u-text">格式：xls .xlsx .xlsm</span>
      </el-upload>
      <div class="u-mt20 u-mb20">
        <el-input
          v-filter-input
          style="width: 200px; margin-right: 10px"
          v-model.trim="buildingValue"
          placeholder="请输入区域ID/名称"
          clearable
          size="small"
        />
        <el-button icon="el-icon-search" type="primary" size="small" @click="queryBuild">查询</el-button>
      </div>
      <el-table :data="tableData" height="400" :row-class-name="changeRow">
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="buildingViewId" label="区域编号" align="center" :render-header="addRedStar">
          <!-- <template slot-scope="scope">
            <span class="icon"></span>
            <span>{{ scope.row.informationName | nullishCoalescing }}</span>
          </template> -->
        </el-table-column>
        <el-table-column
          prop="buildingName"
          label="区域名称"
          align="center"
          :render-header="addRedStar"
        ></el-table-column>
        <el-table-column prop="buildingArea" label="建筑面积（㎡）" align="center"></el-table-column>
        <el-table-column prop="peopleNum" label="办公人数" align="center"></el-table-column>
        <el-table-column prop="sortNum" label="同级别排序号" align="center"></el-table-column>
        <el-table-column
          prop="pBuildingViewId"
          label="上级区域编号"
          align="center"
          :render-header="addRedStar"
        ></el-table-column>
        <el-table-column
          prop="parentName"
          label="上级区域名称"
          align="center"
          :render-header="addRedStar"
        ></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancel2" type="primary" plain>取 消</el-button>
        <el-button type="primary" size="small" @click="saveUpload">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
.insBuild-wrapper {
  > div {
    flex: 1;
    height: 100%;
  }
}
.uploadPic {
  display: flex;
  align-items: flex-end;
}
.uploadPic ::v-deep(.el-upload--picture-card) {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 240px;
  height: 121px;
}
.styleA ::v-deep(.el-upload--picture-card) {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 240px;
  height: 121px;
}
.styleB ::v-deep(.el-upload--picture-card) {
  display: none;
}
.uploadPic ::v-deep(.el-upload-list__item) {
  width: 240px;
  height: 121px;
}
.area-details {
  margin-top: 20px;
  width: 80%;
  > div {
    margin: 20px 0;
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
  }
}
.upload-demo {
  display: flex;
  align-items: flex-end;
}
</style>
